<template>
    <div class="container">
        <!-- 顶部导航 -->
        <div class="top-nav">
            <el-button @click="toggleOrientation">{{ isLandscape ? '竖屏' : '横屏' }}</el-button>
            <el-button @click="savePositions">保存</el-button>
            <el-select v-model="selectedAction" placeholder="选择操作" style="width: 120px; margin-left: 10px;">
                <el-option label="拍照" value="camera" />
                <el-option label="签名" value="signature" />
            </el-select>
        </div>

        <!-- 主内容区 -->
        <div class="main-content">
            <!-- 左侧导航 -->
            <div class="sidebar">
                <div class="nav-buttons">
                    <el-tooltip effect="dark" content="组件设置" placement="right">
                        <div :class="['nav-item', { active: currentTab === 'componentTab' }]"
                            @click="handleTabChange('componentTab')">
                            <el-icon>
                                <Grid />
                            </el-icon>
                        </div>
                    </el-tooltip>

                    <el-tooltip effect="dark" content="页面设置" placement="right">
                        <div :class="['nav-item', { active: currentTab === 'page' }]" @click="handleTabChange('page')">
                            <el-icon>
                                <Picture />
                            </el-icon>
                        </div>
                    </el-tooltip>

                    <div class="nav-bottom">
                        <el-tooltip effect="dark" content="快捷键" placement="right">
                            <div class="nav-item">
                                <el-icon>
                                    <Operation />
                                </el-icon>
                            </div>
                        </el-tooltip>
                    </div>
                </div>
            </div>
            <div class="preview-wrapper">
                <div class="preview-container">
                    <div class="preview-area" ref="previewContainer" :style="previewStyle"
                        :class="isLandscape ? 'landscape' : 'portrait'">
                        <!-- 可拖拽按钮 -->
                        <div v-for="(btn, index) in buttons" :key="btn.id" class="draggable-btn"
                            :style="getButtonStyle(btn)" @mousedown="startDrag(index, $event)"
                            :class="{ 'no-pointer': currentTab === 'page' }">
                            <el-icon class="btn-icon">
                                <component :is="btn.icon" />
                            </el-icon>
                            <span class="btn-text">{{ btn.text }}</span>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- 页面设置抽屉 -->
        <el-drawer v-model="drawerVisible" title="页面设置" direction="rtl" size="30%">
            <page-settings :title="pageTitle" :background-type="backgroundType" :bg-color="backgroundColor"
                @update:title="val => pageTitle = val" @update:background-type="val => backgroundType = val"
                @update:bg-color="val => backgroundColor = val" />
        </el-drawer>
    </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted, nextTick, markRaw } from 'vue' // 添加 markRaw 导入
import { Grid, Picture, Operation, Setting, Camera, Delete, Promotion } from '@element-plus/icons-vue'
import PageSettings from '@/components/clientPageSetting/PageSettings.vue'


const initialButtons = [
    { id: 1, text: '设置', icon: markRaw(Setting), x: 0.1, y: 0.2 },
    { id: 2, text: '拍照', icon: markRaw(Camera), x: 0.3, y: 0.5 },
    { id: 3, text: '清除', icon: markRaw(Delete), x: 0.6, y: 0.3 },
    { id: 4, text: '完成', icon: markRaw(Promotion), x: 0.8, y: 0.7 }
]

const buttons = ref([...initialButtons])
const currentTab = ref('componentTab')
const drawerVisible = ref(false)
const previewContainer = ref(null)
const isDragging = ref(false)
const dragIndex = ref(-1)
const startX = ref(0)
const startY = ref(0)
const pageTitle = ref('默认标题')
const backgroundType = ref('color')
const backgroundColor = ref('#ffffff')
const isLandscape = ref(false)
const selectedAction = ref('camera')

const previewStyle = computed(() => ({
    backgroundColor: backgroundType.value === 'color' ? backgroundColor.value : 'transparent',
}))

const getButtonStyle = (btn) => ({
    left: `${btn.x * 100}%`,
    top: `${btn.y * 100}%`,
    cursor: currentTab.value === 'componentTab' ? 'move' : 'default'
})

const handleTabChange = (tab) => {
    currentTab.value = tab
    drawerVisible.value = tab === 'page'
}

const startDrag = (index, e) => {
    if (currentTab.value !== 'componentTab') return

    const containerRect = previewContainer.value.getBoundingClientRect()
    const offsetX = e.clientX - containerRect.left - buttons.value[index].x * containerRect.width
    const offsetY = e.clientY - containerRect.top - buttons.value[index].y * containerRect.height

    isDragging.value = true
    dragIndex.value = index
    startX.value = offsetX
    startY.value = offsetY

    document.addEventListener('mousemove', onDrag)
    document.addEventListener('mouseup', stopDrag)
}

const onDrag = (e) => {
    if (!isDragging.value) return

    const containerRect = previewContainer.value.getBoundingClientRect()
    const containerWidth = containerRect.width
    const containerHeight = containerRect.height

    const mouseX = e.clientX - containerRect.left - startX.value
    const mouseY = e.clientY - containerRect.top - startY.value

    const newX = Math.max(0.04, Math.min(mouseX / containerWidth, 0.96))
    const newY = Math.max(0.04, Math.min(mouseY / containerHeight, 0.96))

    buttons.value[dragIndex.value].x = newX
    buttons.value[dragIndex.value].y = newY
}

const stopDrag = () => {
    isDragging.value = false
    document.removeEventListener('mousemove', onDrag)
    document.removeEventListener('mouseup', stopDrag)
}

const toggleOrientation = () => {
    isLandscape.value = !isLandscape.value
    nextTick(() => {
        handleResize()
    })
}

const savePositions = () => {
    console.log('保存按钮位置：', buttons.value.map(btn => ({ id: btn.id, x: btn.x, y: btn.y })))
}

const handleResize = () => {
    const container = previewContainer.value
    if (!container) return

    const parent = container.parentElement.parentElement // 获取外层容器
    const aspectRatio = isLandscape.value ? 16 / 9 : 9 / 16
    const scaleFactor = isLandscape.value ? 0.9 : 1 // 横屏时缩放系数设为0.9

    if (parent.offsetWidth / parent.offsetHeight > aspectRatio) {
        container.style.width = `${parent.offsetHeight * aspectRatio * scaleFactor}px`
        container.style.height = `${parent.offsetHeight * scaleFactor}px`
    } else {
        container.style.width = `${parent.offsetWidth * scaleFactor}px`
        container.style.height = `${(parent.offsetWidth / aspectRatio) * scaleFactor}px`
    }
}

onMounted(() => {
    handleResize()
    window.addEventListener('resize', handleResize)
})

onUnmounted(() => {
    window.removeEventListener('resize', handleResize)
})
</script>

<style scoped>
.container {
    display: flex;
    flex-direction: column;
    height: 100vh;
    background: #f0f2f5;
}

.top-nav {
    height: 60px;
    background: #fff;
    display: flex;
    align-items: center;
    padding: 0 20px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.main-content {
    flex: 1;
    display: flex;
    min-height: 0;
}

.sidebar {
    width: 60px;
    background: #f5f7fb;
    padding: 20px 0;
}

.nav-buttons {
    display: flex;
    flex-direction: column;
    align-items: center;
    height: 100%;
}

.nav-item {
    width: 40px;
    height: 40px;
    margin: 10px 0;
    display: flex;
    align-items: center;
    justify-content: center;
    border-radius: 8px;
    cursor: pointer;
    transition: all 0.3s;
}

.nav-item.active {
    background: #34495e;
    color: #3498db;
}

.preview-wrapper {
    flex: 1;
    display: flex;
    justify-content: center;
    align-items: center;
    overflow: hidden;
    padding: 20px;
}

.preview-container {
    position: relative;
    transition: transform 0.3s;
}

.preview-area {
    background: white;
    box-shadow: 0 4px 24px rgba(0, 0, 0, 0.2);
    position: relative;
    transition: all 0.3s;
}

.landscape {
    transform: scale(0.9);
    /* 横屏时应用缩放 */
    transform-origin: center;
}

.portrait {
    transform: scale(1);
}

.draggable-btn {
    position: absolute;
    display: flex;
    flex-direction: column;
    align-items: center;
    transform: translate(-50%, -50%);
    padding: 8px;
    user-select: none;
}

.btn-icon {
    font-size: 24px;
    margin-bottom: 4px;
}

.btn-text {
    font-size: 12px;
    white-space: nowrap;
}

.no-pointer {
    pointer-events: none;
}
</style>